import path from "path"
import typescript from "rollup-plugin-typescript2"
import json from "@rollup/plugin-json"
import nodeResolve from "@rollup/plugin-node-resolve"
import commonjs from "@rollup/plugin-commonjs"
import babel from "@rollup/plugin-babel"

function createConfig(packageName, filename, distFilename) {

  const packagePath = path.resolve(__dirname, "packages", packageName)
  const { dependencies } = require(path.resolve(packagePath, "package.json"))

  const extraOutput = {}

  if (packageName === "shared" && filename === "position") {
    extraOutput.exports = "default"
  }

  return {
    input: `./packages/${packageName}/src/${filename}.ts`,
    output: [{
      file: `./packages/${packageName}/dist/${distFilename === undefined ? filename : distFilename}.js`,
      format: "cjs",
      ...extraOutput,
    }],
    external: [
      "axios", "tslib", "lodash",
      "@mallfoundry/client/case",
      "@mallfoundry/client/http",
      "@mallfoundry/client/axios",
      "@mallfoundry/client/message",
      "@mallfoundry/shared/data",
      "@mallfoundry/shared/ownership",
      "@mallfoundry/shared/position",
      ...Object.keys(dependencies === undefined ? {} : dependencies),
    ],
    plugins: [
      json(),
      babel({
        babelHelpers: "bundled",
      }),
      typescript({
        tsconfig: path.resolve(__dirname, "tsconfig.json"),
        tsconfigOverride: {
          compilerOptions: {
            declaration: true,
            declarationMap: true,
          },
        },
      }),
      nodeResolve({
        preferBuiltins: true,
      }),
      commonjs({ extensions: [".js", ".ts"] }),
    ],
  }
}

export default [
  createConfig("client", "index"),
  createConfig("client", "axios"),
  createConfig("client", "case"),
  createConfig("client", "message"),
  createConfig("shared", "data"),
  createConfig("shared", "position"),
  createConfig("shared", "ownership"),
  createConfig("keystone", "identity/index", "identity"),
  createConfig("keystone", "security/index", "security"),
  createConfig("shipping", "index"),
  createConfig("catalog", "index"),
  createConfig("captcha", "index"),
  createConfig("cart", "index"),
  createConfig("checkout", "index"),
  createConfig("order", "index"),
  createConfig("marketing", "coupon"),
  createConfig("store", "index"),
  createConfig("store", "staff"),
  createConfig("discuss", "index"),
]
